package com.cj.bigfileupload.common.exception;

import com.cj.bigfileupload.common.Response;
import com.cj.bigfileupload.common.i18n.MessageManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: ControllerExceptionAdvice <br/>
 * Function: 处理Controller层抛出的异常 <br/>
 * date: 2018/05/08 15:33 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
@ControllerAdvice
public class ControllerExceptionAdvice {

    private static final Logger LOGGER = Logger.getLogger(ControllerExceptionAdvice.class);

    @Autowired
    private MessageManager messageManager;

    /**
     * 业务异常
     * 该异常是需要让调用者知道详细的错误信息，返回具体的错误信息
     *
     * @param request
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Response handleBusinessException(HttpServletRequest request,
                                            BusinessException ex) {
        return Response.failure(ex.getCode(), messageManager.getMessage(ex.getCode(), ex.getArgs()));
    }


    /**
     * 总的异常（Exception只有在找不到异常类型绑定时才会到达这里处理）
     * 这些异常无须让调用者知道，属于系统内部错误
     *
     * @param ex
     * @return
     * @Description:
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Response handleException(HttpServletRequest request, Exception ex) {
        String requestURI = request.getRequestURI();
        LOGGER.error("[" + requestURI + "] get exception", ex);
        return Response.failure(messageManager.getMessage("error.common.internal"));
    }
}
